﻿// See https://aka.ms/new-console-template for more information
using Microsoft.Win32;
using System.Management;
using System.Security.Cryptography;
using System.Text;

Console.WriteLine("正在生成Key");
byte[] key = WriteKey.GenerateKeyByte();
Console.WriteLine("正在写入Key");
if (OperatingSystem.IsWindows() )
{
    var regKey= Registry.CurrentUser.OpenSubKey("Software\\NSmartProxy",true);
    if (regKey == null)
    {
        regKey=Registry.CurrentUser.OpenSubKey("Software", true)!.CreateSubKey("NSmartProxy");
    }
    regKey.SetValue("key",key,RegistryValueKind.Binary);
    Console.WriteLine("写入Key完成");
}

class WriteKey
{
    public static string GenerateKey()
    {
        // 获取硬盘序列号等硬件信息作为密钥的一部分
        string hardwareId = GetHardwareId();
        using (SHA256 sha256Hash = SHA256.Create())
        {
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(hardwareId));
            bytes = MD5.HashData(bytes);
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("X2"));
            }
            return builder.ToString();
        }
    }
    public static byte[] GenerateKeyByte()
    {
        // 获取硬盘序列号等硬件信息作为密钥的一部分
        string hardwareId = GetHardwareId();
        using (SHA256 sha256Hash = SHA256.Create())
        {
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(hardwareId));
            bytes = MD5.HashData(bytes);
            
            return bytes;
        }
    }
    private static string GetHardwareId()
    {
        string hardwareId = string.Empty;
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); // 获取硬盘序列号等硬件信息，根据需要选择合适的类和方法。例如：Win32_Processor, Win32_VideoController等。
        foreach (ManagementObject wmi_MO in searcher.Get())
        {
            if (wmi_MO == null)
            {
                continue;
            }
            hardwareId += wmi_MO["SerialNumber"]?.ToString(); // 例如，从硬盘序列号获取信息。根据需要选择合适的属性。
        }
        if (string.IsNullOrEmpty(hardwareId))
        {
            hardwareId=Environment.MachineName;
            Console.WriteLine("没有获取到SerialNumber，取计算机名");
        }
        return hardwareId; // 返回硬件信息的字符串表示。根据实际情况可能需要处理或拼接多个硬件ID。
    }

}